﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Aribaccio
{
    /// <summary>
    /// 属性通知类基类[自定义]
    /// </summary>
    [Serializable]
    public class NotificationObject : INotifyPropertyChanged
    {
        [NonSerialized]
        private NotificationStatus _Status;
        /// <summary>
        /// 数据状态
        /// </summary>
        [Browsable(false)]
        public NotificationStatus Status { get { return _Status; } set { _Status = value; } }
        /// <summary>
        /// 
        /// </summary>
        [field: NonSerialized]
        public event PropertyChangedEventHandler? PropertyChanged;

        /// <summary>
        /// 设置通知属性变更
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="argItem"></param>
        /// <param name="argValue"></param>
        protected virtual void NotifyPropertySet<T>(ref T argItem, T argValue)
        {
            if (!EqualityComparer<T>.Default.Equals(argItem, argValue))
            {
                argItem = argValue;
                NotifyPropertyChanged(() => argValue);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        protected virtual void NotifyPropertyChanged<T>(Expression<Func<T>> action)
        {
            var propertyName = GetPropertyName(action);
            RaisePropertyChanged(propertyName);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <returns></returns>
        private static string GetPropertyName<T>(Expression<Func<T>> action)
        {
            var expression = (MemberExpression)action.Body;
            return expression.Member.Name;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="propertyName"></param>
        protected void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                if (Status != NotificationStatus.Added) { Status = NotificationStatus.Modified; }
            }
        }
    }
}
